import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class RightSideView {

    public List<Integer> rightSideView1(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        if (root == null) return ans;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        TreeNode node = null;
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = size; i > 0; i--) {
                node = queue.poll();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            ans.add(node.val);
        }
        return ans;
    }

    List<Integer> ans = new ArrayList<>();
    public List<Integer> rightSideView(TreeNode root) {
        process(root, 0);
        return ans;
    }

    public void process(TreeNode node, int depth) {
        if (node == null) return;
        if (ans.size() == depth) {
            ans.add(node.val);
        }
        ++depth;
        process(node.right, depth);
        process(node.left, depth);
    }
}
